var qqmap = require('./vendor/qqmap-sdk.min.js');

App({
  onLaunch: function () {
    var that = this
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        traceUser: true,
      })
    }
    this.globalData = {}
  },
  getpol: function (cb) {
    var that = this
    if (!that.globalData.userInfo){

    }
    wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var lat = res.latitude
          var lon = res.longitude
          var demo = new qqmap({
              key: 'SZBBZ-DARAP-ACWDA-VN2QZ-XO4F5-3UBNM'
          });
          that.globalData.lat = lat;
          that.globalData.lon = lon;
          demo.reverseGeocoder({
              location: {
                  latitude: lat,
                  longitude: lon
              },
              success: function (res) {
                console.log(res);
                  var acc = res.result.address_component.city
                  console.log(acc)
                  var len = acc.length
                  var last = acc.charAt(len - 1)
                  if (last === '市') {
                      var positionCity = acc.slice(0, -1)
                      that.globalData.positionCity = positionCity
                  }
                  else {
                      that.globalData.positionCity = acc
                  }
                  var recity = wx.getStorageSync('recity') || []
                  if (recity.length) {
                      that.globalData.currentCity = recity[0]
                      if (!that.globalData.remind & recity[0] != that.globalData.positionCity) {
                          wx.showModal({
                              title: '',
                              content: '定位到您当前所在的城市在' + that.globalData.positionCity + ',是否切换',
                              success: function (res) {
                                if(res.confirm){
                                  that.globalData.currentCity = that.globalData.positionCity
                                  recity.unshift(that.globalData.positionCity)
                                  var nowrecity = recity.slice(0, 2)
                                  wx.setStorageSync('recity', nowrecity)
                                  typeof cb == "function" && cb(that.globalData.positionCity)
                                }else{
                                  typeof cb == "function" && cb(that.globalData.currentCity)
                                }
                              }
                          })
                          that.globalData.remind = true
                      }else{
                        typeof cb == "function" && cb(that.globalData.currentCity)
                      }
                  }
                  else {
                      that.globalData.currentCity = that.globalData.positionCity
                      typeof cb == "function" && cb(that.globalData.currentCity)
                  }
              }
          });
        }
    })
  },
  setUserInfo: function (userinfo, cb){
    this.globalData.userInfo = userinfo;
    //获取到openid开始校验登陆
    this.choiceLogin(cb);
  },
  login: function (cb){
    //if (!this.globalData.userInfo)return;
    var service = require('util/service');
    service.AJAX(`smc/base/SystemBuyerUser/choiceLoginTo.do?openId=${this.globalData.openid}`, {}, res => {
      if (cb) cb(res);
      if (res && res.pic && res.pic != "") {
        this.userInfo = res;
      } else {
        if (!this.globalData.userInfo) return;
        service.AJAX(`smc/base/SystemBuyerUser/choiceLoginTo.do?openId=${this.globalData.openid}`, {}, res => {
          if (res) {
            this.updateUser(res);
          }
        }, err => { }, "POST")
      }
    }, err => { }, "POST")
  },
  choiceLogin:function(cb){
    var that = this;
    if (that.globalData.openid){
      that.login(cb);
    }else{
      // 调用云函数
      wx.cloud.callFunction({
        name: 'login',
        data: {},
        success: res => {
          that.globalData.openid = res.result.userInfo.openId;
          that.login(cb);
        }
      })
    }
  },
  //更新用户信息
  updateUser:function(user){
    var service = require('util/service');
    var avatarUrl = this.globalData.userInfo.avatarUrl;
    var time = new Date().getTime();
    user.nameForWx = user.nameForWx||this.globalData.userInfo.nickName;
    user.weixinName = user.weixinName||this.globalData.userInfo.nickName;
    user.picForWx = avatarUrl;
    user.pic = avatarUrl;
    user.openId = this.globalData.openid;
    user.buyName = user.buyName ||this.globalData.userInfo.nickName;
    user.buyCode = user.buyCode || ("WX" + avatarUrl.substr(45, 5) + (time+"").substr(8,5));//编码-账号
    user.buyLevelId = user.buyLevelId || 5;//等级
    user.money = user.money || 0;//熊仔币
    user.buyDesc = user.buyDesc || "空空如也";//个人介绍
    user.locked = user.locked || false;//是否失效
    user.commentsNumber = user.commentsNumber || 0;
    user.thumbsNumber = user.thumbsNumber || 0;
    user.vipLevel = user.vipLevel || false;
    delete user.createdAt;
    delete user.lastedUpdAt;
    delete user.vipEndEffe;
    delete user.lastedUpdBy;
    delete user.createdBy;

    //更新微信用户信息以及平台用户信息
    service.AJAX(`smc/base/SystemBuyerUser/updSystemBuyerUser.do`, user, res => { this.choiceLogin()}, err => { }, "POST");
    //更新微信用户信息以及平台用户信息
    service.AJAX(`smc/base/WeixinUser/updWeixinUser.do`, user, res => { }, err => { }, "POST")
  },
  getGlobalData:function(){
    return this.globalData;
  },
  globalData: {
    userInfo: null,
    openid:null,
    positionCity: '',
    currentCity: '',
    lat:'',
    lon:'',
    remind: false
  },
  tabbar: {
    "color": "#6A6767",
    "selectedColor": "#F52C56",
    "backgroundColor": "#F5F5F5",
    "list": [
      {
        "pagePath": "../../pages/index/index",
        "text": "首页",
        "iconPath": "../../images/tab/1.png",
        "selectedIconPath": "../../images/tab/1s.png"
      },
      {
        "pagePath": "../../pages/information/information",
        "text": "资讯",
        "iconPath": "../../images/tab/2.png",
        "selectedIconPath": "../../images/tab/2s.png"
      },
      {
        "pagePath": "../../pages/collection/collection",
        "text": "收藏",
        "iconPath": "../../images/tab/3.png",
        "selectedIconPath": "../../images/tab/3s.png"
      },
      {
        "pagePath": "../../pages/my/my",
        "text": "我",
        "iconPath": "../../images/tab/4.png",
        "selectedIconPath": "../../images/tab/4s.png"
      }
    ]
  },
  changeTabBar: function () {
    var _curPageArr = getCurrentPages();
    var _curPage = _curPageArr[_curPageArr.length - 1];
    var _pagePath = _curPage.__route__;
    // if (_pagePath.indexOf('/') != 0) {
    _pagePath = '../../' + _pagePath;
    // }
    var tabBar = this.tabbar;
    for (var i = 0; i < tabBar.list.length; i++) {
      console.log(_pagePath + '--' + tabBar.list[i].pagePath)
      tabBar.list[i].selected = false;
      if (tabBar.list[i].pagePath == _pagePath) {
        tabBar.list[i].selected = true;//根据页面地址设置当前页面状态  
      }
    }
    _curPage.setData({
      tabbar: tabBar
    });
  }
})
